#include "TransferRvdcData.h"
#include <log/log.h>

TransferRvdcData::TransferRvdcData() {
    mLogname = new char[totalLength];
    memset(mLogname, 0, totalLength);
    mChunkPayload = new uint8_t[totalLength];
    memset(mChunkPayload, 0, totalLength);
}

TransferRvdcData::~TransferRvdcData() {
    if (mLogname != NULL) {
        delete[] mLogname;
        mLogname = NULL;
    }
    if (mChunkPayload != NULL) {
        delete[] mChunkPayload;
        mChunkPayload = NULL;
    }
}

std::string TransferRvdcData::toString(uint8_t* buf, size_t size) {
    std::stringstream ioss;
    std::string s_temp;
    for (size_t i = 0; i < size; i++) {
        ioss << std::uppercase << std::hex << std::setw(2) << std::setfill('0') << int(*(buf + i));
    }
    ioss >> s_temp;
    return s_temp;
}

int TransferRvdcData::getDecNum(const char* buf, int seq, int length) {
    char* tmp_buffer = new char[length];
    memset(tmp_buffer, 0, length);
    memcpy(tmp_buffer, buf + seq, length);
    int num = str2hex(toString((uint8_t*)tmp_buffer, length));
    delete[] tmp_buffer;
    return num;
}

int TransferRvdcData::str2hex(std::string str) {
    std::stringstream ioss;
    int i_temp;
    ioss << std::hex << str;
    ioss >> i_temp;
    return i_temp;
}

void TransferRvdcData::parseRVDCBuf(const char* buf) {
    try {
        this->mTransfertype = buf[TRANSFER_TYPE_SEQ];
        this->mReserved = buf[TRANSFER_RESERVED_SEQ];
        memcpy(this->mLogname, buf + TRANSFER_LOGNAME_SEQ, TRANSFER_LOGNAME_SIZE);
        this->mChunknumber = getDecNum(buf, TRANSFER_CHUNKNUM_SEQ, TRANSFER_DATASIZE);
        this->mFileSize = getDecNum(buf, TRANSFER_FILESIZE_SEQ, TRANSFER_DATASIZE);
        this->mChunkSize = getDecNum(buf, TRANSFER_CHUNKSIZE_SEQ, TRANSFER_SHORT_DATASIZE);
        memcpy(this->mChunkPayload, buf + TRANSFER_CHUNKPAYLOAD_SEQ, this->mChunkSize);
        ALOGD("RVDC Transfertype %d", this->mTransfertype);
        ALOGD("RVDC Reserved %d", this->mReserved);
        ALOGD("RVDC Logname %s", this->mLogname);
        ALOGD("RVDC Chunknumber %d", this->mChunknumber);
        ALOGD("RVDC fileSize %d", this->mFileSize);
        ALOGD("RVDC ChunkSize %d", this->mChunkSize);
    } catch (std::exception& e) {
        ALOGD("exception : %s", e.what());
    }
}